<template>
  <div class="search-container">
    <div style="margin-top: 20px">
      <el-radio-group v-model="searchType" size="mini">
        <el-radio-button v-model="searchType" label="1">书籍</el-radio-button>
        <el-radio-button v-model="searchType" label="2">作者</el-radio-button>
        <el-radio-button v-model="searchType" label="3">类别</el-radio-button>
      </el-radio-group>
    </div>
    <el-input
      v-model="searchStr"
      prefix-icon="el-icon-search"
      clearable
      autofocus
    >
      <template slot="append">
        <el-button type="danger" @click="headleSearch">搜索</el-button>
        <el-button
          type="danger"
          class="handout"
          @click="headleHandout"
        >随便逛逛</el-button>
      </template>
    </el-input>
  </div>
</template>

<script>
import { initBookPageFormAndSearchBookForm } from '@/common/common'

export default {

  data() {
    return {
      searchStr: '',
      searchType: '1'
    }
  },
  computed: {
  },
  created() {
    this.setDefaultSearchStr()
    this.setDefaultSearchType()
  },
  methods: {
    setDefaultSearchStr() {
      if (this.$store.getters.searchBookForm.str) {
        this.searchStr = this.$store.getters.searchBookForm.str
      }
    },
    setDefaultSearchType() {
      this.searchType = this.$store.getters.searchBookForm.type
    },
    headleSearch() {
      initBookPageFormAndSearchBookForm()

      const obj = {
        type: this.searchType,
        str: this.searchStr,
        getBooksByCid: false,
        cid: '',
        orderType: 1,
        from: '',
        to: ''
      }
      this.$store.commit('book/SET_SEARCHBOOKFORM', obj)
      this.$store.dispatch('book/searchBook').then(res => {
        if (!this.$route.fullPath.includes('/book')) {
          this.$router.push('/book')
        }
        if (this.$route.fullPath.startsWith('/bookDetail')) {
          this.$router.push('/book')
        }
      }).catch(() => {
        const obj = {
          type: this.searchType,
          str: '',
          getBooksByCid: false,
          cid: '',
          orderType: 1,
          from: '',
          to: ''
        }
        this.$store.commit('book/SET_SEARCHBOOKFORM', obj)
      })
    },

    // 随便逛逛，跳转到/book路由
    headleHandout() {
      initBookPageFormAndSearchBookForm()
      this.searchStr = ''
      this.searchType = '1'
      this.$store.dispatch('book/getList').then(res => {
        const date = new Date()
        this.$router.push('/book/' + date.getTime())
      })
    }

  }
}
</script>

<style scoped lang="scss">

.search-container {
  width: 500px;
  // margin: 0 auto;
}
.handout {
  border-left: 1px solid;
}
.el-button:hover {
  color: #529cd6;
}

</style>
